import { defineStore } from "pinia";
import { ref } from "vue";
import pagesJson from "@/pages.json";
import { getPage } from "@/uni_modules/pure-utils";

export const useTabbarStore = defineStore("tabbar", () => {
	// pages.json 中配置的 tabbar 数据
	const tabBar = pagesJson.tabBar;

	// 定义 tabbar 数据
	const list = ref(tabBar?.list || []);

	// 定义 tabbar 选中项
	const value = ref(list.value?.[0]?.pagePath);

	/**
	 * 切换 tabbar
	 * @param {Object} item - tabbar 项
	 */
	function change(item) {
		value.value = item?.value || item?.pagePath;
		uni.switchTab({ url: `/${item?.pagePath}` });
	}

	/**
	 * 更新 tabbar 选中项的值为当前页面对应的值
	 */
	function updateValue() {
		const page = getPage();
		const item = list.value.find((item) => item.pagePath === page.path);
		if (item) {
			value.value = item.value || item.pagePath;
		}
	}

	return { list, value, change, updateValue };
});
